﻿using Entitas;
using Entitas.Unity;
using UnityEngine;

/// <summary>
/// Unity Mono gameObj
/// </summary>
public class View : MonoBehaviour,IView,IDestoryCompListener
{
    protected GameEntity _selfEntity=>gameObject.GetEntityLink ().entity as GameEntity;
    
    public void Link (Contexts contexts, IEntity entity)
    {
        gameObject.Link (entity);

        var gameEntity = (GameEntity) entity;
        gameEntity.AddDestoryCompListener (this);
        
        transform.position = gameEntity.posComp.pos;
        transform.rotation=Quaternion.Euler (0,0,gameEntity.rotComp.angle); 
        OnLinkEntityHandler ();
    }

    public void OnDestoryComp (GameEntity entity)
    {
        gameObject.Unlink ();
        OnDestoryEntityHandler ();
    }
    
    private void OnCollisionEnter2D (Collision2D other)
    {
        var selfEntity  = _selfEntity;
        var otherEntity = other.gameObject.GetEntityLink ().entity as GameEntity;

        if (otherEntity != null)
            GameManager.contexts.physics.physicComp.collisionInfoList.Add (new CollisionInfo ()
            {
                sourceId = selfEntity.id.value,
                otherId  = otherEntity.id.value
            });
    }
    
    private void OnTriggerEnter2D (Collider2D other)
    {
        var selfEntity  = _selfEntity;
        var otherEntity = other.gameObject.GetEntityLink ().entity as GameEntity;

        if (otherEntity != null)
            GameManager.contexts.physics.physicComp.collisionInfoList.Add (new CollisionInfo ()
            {
                sourceId = selfEntity.id.value,
                otherId  = otherEntity.id.value
            });
    }

    protected virtual void OnLinkEntityHandler ()
    {
        
    }

    protected virtual void OnDestoryEntityHandler ()
    {
        
    }
}